﻿using bilibili下载.Interface;
using HttpHelper;
using Newtonsoft.Json;
using NLog;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows.Media.Imaging;

namespace bilibili下载.Models
{
    public class AVAnalysis : IAnalysis
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        public AVAnalysis(string avId)
        {
            avId = avId.ToLower().Replace("av", null);
            WinHttp http = new WinHttp();
            var query = new Dictionary<string, string>
            {
                ["aid"] = avId,
                ["jsonp"] = "json",
            };
            aVInfos = new List<AVInfo>();
            logger.Debug("开始获取AvId：{0}", avId);
            http.Open(Method.GET, "https://api.bilibili.com/x/web-interface/view", query);
            var data = http.Send();
            if (data.IsSuccessStatus)
            {
                logger.Debug("AvId：{0},内容：{1}", avId, data.Text);
                var result = JsonConvert.DeserializeObject<AvResponse>(data.Text);
                if (result.code == 0)
                {
                    if (result?.data?.pages?.Length > 0 && !string.IsNullOrEmpty(result.data.pic))
                    {
                        logger.Debug("AvId：{0},开始获取封面图片", avId);
                        http.Open(Method.GET, result.data.pic);
                        data = http.Send();
                        BitmapImage image = null;
                        if (data.IsSuccessStatus)
                        {
                            image = new BitmapImage();
                            image.BeginInit();
                            image.StreamSource = new MemoryStream(data.Body);
                            image.EndInit();
                        }
                        else logger.Debug("AvId：{0},封面图片获取失败", avId);
                        var id = 0;
                        foreach (var item in result.data.pages)
                        {
                            aVInfos.Add(new AVInfo(avId, item.cid)
                            {
                                Name = item.part,
                                Id = ++id,
                                Image = image,
                            });
                        }
                    }
                    else logger.Debug("AvId：{0},视频地址或封面图片地址错误", avId);
                }
                else logger.Debug("AvId：{0},解析失败", avId);
            }
            else logger.Debug("AvId：{0},获取失败.状态码：{1}.状态信息：{2}.错误描述：{3}", avId, data.StatusCode, data.Status, data.Message);
        }

        private List<AVInfo> aVInfos;

        public IEnumerator<IAVInfo> GetEnumerator()
        {
            return aVInfos.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        private class AvResponse
        {
            public int code { get; set; }
            public string message { get; set; }
            public AvData data { get; set; }
        }

        private class AvData
        {
            public string pic { get; set; }

            public AvPage[] pages { get; set; }
        }

        private class AvPage
        {
            public string cid { get; set; }

            public string part { get; set; }
        }
    }
}